<template>
	<view class="predetermine">
		<view class="status_bar_h" :style="{
				height: `${statusBarHeight}px`,
				backgroundColor: '#20BF6C',
			}"></view>
		<view class="img_box">
			<!-- <swiper
				style="height: 400rpx"
				circular
				:indicator-dots="false"
				:autoplay="true"
				:interval="2000"
				:duration="500">
				<swiper-item
					v-for="(item, key) in src"
					:key="key">
					<view class=""
						><image
							style="width: 100%; height: 400rpx"
							mode="aspectFill"
							:src="item"></image
					></view>
				</swiper-item>
			</swiper> -->
			<image style="width: 100%; height: 400rpx" mode="aspectFill" :src="src">
			</image>
			<view class="back" @click="retreat">
				<image src="/static/images/arrow-left.png" mode="widthFix"></image>
				<text>返回</text>
			</view>

			<view class="count_down">
				<u-count-down :time="5*60*1000" format="ss"></u-count-down>
				<text>s後將自動登出</text>
			</view>

		</view>
		<view class="main">
			<view class="title">
				<view class="store">{{ view.store }}</view>
				<view class="info">
					<text>歡迎您：</text>
					<text>{{view.user.mobile?view.user.mobile:view.user.user.mobile }} |
					</text>
					<text>
						{{ view.user.mobile?view.user.level === 0 ? '普通會員':'' : view.user.user.level === 0 ? '普通會員' : '' }}
						| </text>
					<text @click="logout">退出</text>
				</view>
			</view>
			<view class="room_info">
				<view class="room_info_box">
					<view class="room_info_l">
						<up-image :show-loading="true" :src="tipsImg" width="230rpx" height="174rpx"></up-image>
					</view>
					<view class="room_info_r">
						<view class="">請投入現金</view>
						<view class="tips">
							<view class="tips_title">注意：</view>
							<!-- <u-notice-bar direction="column" duration="5000" :text="notice"></u-notice-bar> -->
							<view class="tips_item">1.找零只找50元</view>
							<view class="tips_item">2.現金只收1000/500/100鈔票及50元硬幣</view>
							<view class="tips_item">3.系統將於5分鐘後自動登出</view>
						</view>


					</view>
				</view>
			</view>
			<view class="ticket_box">
				<u-cell-group>
					<u-cell title="訂單編號" :isLink="false" :value="view.order_no"></u-cell>
					<u-cell title="應付款" :isLink="false"
						:value="view.order.money?view.order.money:view.order.disbursements"></u-cell>
					<u-cell title="已付款" :isLink="false" :value="analysisCountMoney(messageSumArr)"></u-cell>
					<!-- <u-cell title="找零" :isLink="false" :value="view.order.room_type_name"></u-cell> -->
					<u-cell title="找零" :isLink="false" :value="`${change} * 50`"></u-cell>
				</u-cell-group>

			</view>
		</view>
		<view class="notice">
			<u-notice-bar bgColor="#fff" color="#39B19D" :text="text1"></u-notice-bar>
		</view>

		<!-- 纸币找零提示 -->
		<u-popup round="10" :show="showZBZLPopup" mode="center">
			<view class="zl_popup">
				<view class="zl_popup_item">應找零：50 * {{change}}</view>
				<view class="zl_popup_item">已找零：50 * {{changed}}</view>
				<u-button class="custom-style3" text="確定" @click="confirmZLFinish"></u-button>
			</view>
		</u-popup>
		<!-- 找零硬幣不足 -->
		<u-modal @confirm="contactService" confirmText="確認" :show="showCoinInsufficient" title="當前硬幣不足,請聯繫客服人員">
		</u-modal>




	</view>
</template>

<script>
	import useStore from '@/store/index.js';
	import baseURL from '@/utils/baseURL.js';
	import {
		getOrderCode,
		saveSlotLog,
		saveSlotPay,
		getOrderList,
		orderContinuation,
		cacheChangeStatus
	} from '@/api/order';
	import {
		zbCode,
		ybCode,
		zlCode,
		stateCode
	} from '@/config/code';
	import {
		countZLSend,
		countMoney
	} from '@/utils/countMoney';
	import ErrorTip from './components/errorTip.vue';
	import zbTips from './components/zbTips.vue'; // 确认纸币投币
	import zbPendingTips from './components/zbPendingTips.vue'; // 纸币投币过程提示
	import zlPendingTips from './components/zlPendingTips.vue'; // 找零过程提示
	import zbSuccessTips from './components/zbSuccessTips.vue'; // 纸币投币总数满足需要的投币数
	import tbPendingTips from './components/tbPendingTips.vue'; // 硬币投币总数满足需要的投币数
	import tbSuccessTips from './components/tbSuccessTips.vue'; // 硬币投币总数满足需要的投币数
	import zlTips from './components/zlTips.vue';
	import ybTips from './components/ybTips.vue';
	import CustomErrorPay from './components/customErrorPay.vue';
	import {
		LogCat
	} from '@/utils/logCat';
	import {
		clearTime,
		timeOut
	} from '@/utils/timeoutToIndex.js'


	const zbSerialPort = uni.requireNativePlugin('Fvv-UniSerialPort');

	const ybSerialPort = uni.requireNativePlugin('Fvv-UniSerialPort2');

	const zlSerialPort = uni.requireNativePlugin('Fvv-UniSerialPort3');

	// import {
	// 	zbSerialPort
	// } from '@/utils/zbSerialPort.js'

	export default {
		components: {
			ErrorTip,
			zbTips,
			zbPendingTips,
			zlPendingTips,
			zbSuccessTips,
			tbSuccessTips,
			zlTips,
			ybTips,
			tbPendingTips,
			CustomErrorPay,
		},
		data() {
			return {
				src: [],
				text1: '請投入金額1000/500/100/50',
				tipsImg: '/static/images/1.jpg',
				baseURL,
				isChecked: false,
				disabled: false,
				isZBOpen: false, // 纸币串口是否打开
				isYBOpen: false, // 硬币串口是否打开
				isZLOpen: false, // 找零串口是否打开
				isCouponShow: false,
				isPayShow: false,
				isErrorTipShow: false, // 找零异常提示
				isZBTipShow: false, // 纸币投币提示
				isYBTipShow: false, // 硬币投币提示
				isYBPendingTipShow: false, // 硬币投币过程提示
				isZLTipShow: false, // 找零提示
				isZLPendingTipShow: false, // 找零过程提示	
				isZLSuccessTipShow: false, // 找零过程提示
				isZBPendingTipShow: false, // 纸币投币过程显示
				isZBSuccessTipShow: false, // 纸币投币总数满足
				isTBSuccessTipShow: false, // 硬币投币总数满足
				select: {
					recType: 'Hex',
					sendType: 'Hex',
					zbUrl: '/dev/ttyUSB10', // 纸币串口路径
					ybUrl: '/dev/ttyUSB10', // 硬币串口路径
					zlUrl: '', // 找零串口路径
					baudRate: 9600,
					sendHexText: '02', // 16进制格式确认要传的参数
				},
				view: {
					ticket: {},
					order: {}, // 详细支付订单
					user: {},
					store: '',
					coupon: '',
					count: 0,
					couponMoney: 0,
					order_no: '', //订单编号
				},
				form: {},
				statusBarHeight: 0, // 顶部状态栏高度
				bthHeight: 0, // 底部按钮高度
				list: [],
				payTypeIndex: -1,
				options: {
					coupon: [],
				},
				scrollTop: 0,
				old: {
					scrollTop: 0,
				},
				messageZBArr: [], // 纸币串口返回的数据的数组集合
				messageZBSendArr: [], // 纸币串口发送的数据的数组集合
				messageYBArr: [], // 硬币串口返回的数据的数组集合
				messageYBSendArr: [], // 硬币串口发送的数据的数组集合
				messageZLArr: [], // 纸币串口返回的数据的数组集合
				messageZLSendArr: [], // 纸币串口发送的数据的数组集合
				page: 1,
				payable: 0, // 应付款
				disbursements: 0, // 实付款
				change: 0, // 应找零
				changed: 0, //  已找零
				changedArr: [],
				timer: null,
				coinTimer: null,
				isPayErrorShow: false, // 支付错误或失败
				paid: '0', // 已付款
				showZBPopup: false,
				showIsZBCoining: false,
				showZBZLPopup: false,
				committedZBArr: [], // 已投入紙幣的數組
				instructArr: [],
				showCoinInsufficient: false,
				showYBPopup: false,
				messageSumArr: [],
				coninInsufficient: false, // 硬币不足
				showPopup: false,
				submittedMoney: 0, //  已投入金額
				payflag: true,
				orderId: '',
				longTime: false,
				delayer: null,
				backTimer: null,
				extendFlag: false,
				quit: null,
				notice: ['1.找零只找50元', '2.現金只收1000/500/100鈔票及50元硬幣', '3.系統將於5分鐘後自動登出'],
				isBack: false,
				payoutFinished: [],
				zlcurrent: 0,
			};
		},
		onLoad(option) {
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
			this.bthHeight = uni.getSystemInfoSync().screenHeight - (1000 - 40) / 2;
			const userOptions = JSON.parse(uni.getStorageSync('userOptions'));
			const equipmentOptions = JSON.parse(uni.getStorageSync('equipmentOptions'));
			const {
				order,
				user,
				room,
				times
			} = useStore();

			this.delayer = setInterval(() => {
				this.longTime = times.getLongTIme
			}, 10 * 1000)

			// 判斷是否是續單的，  true--續單   false--預約訂單
			this.extendFlag = order.getExtendFlag

			this.form = {
				...user.ticket,
				coupon: ''
			};
			this.view = {
				ticket: user.ticket,
				order: order.getOrderObj,
				user: userOptions,
				store: equipmentOptions.name,
				coupon: '',
				order_no: option.orderNo,
			};

			// console.log(this.view.order, '訂單詳情')

			// 應付款
			this.payable = this.view.order.money
			this.setSwiperImg();
			this.countdown();
			// this.getOrderCode();
			// console.log('view', this.view);
			clearTimeout(this.quit)

			this.quit = setTimeout(() => {
				this.logout()
			}, 5 * 60 * 1000)

		},
		onUnload() {
			this.send('zb', zbCode.money_disabled)
			setTimeout(() => {
				this.close('zb')
			}, 500)
			this.send('yb', ybCode.disable)
			setTimeout(() => {
				this.close('yb')
			}, 500)

			this.close('zl')

			clearTimeout(this.timer);
			clearInterval(this.delayer);
			clearTimeout(this.backTimer);
			clearTimeout(this.quit)
		},
		onShow() {

			// 進來自動打開紙幣投入串口
			this.handPay(4)
		},
		onHide() {
			// if (this.showZBPopup) {
			this.send('zb', zbCode.money_disabled)
			setTimeout(() => {
				this.close('zb')
			}, 500)
			this.send('yb', ybCode.disable)
			setTimeout(() => {
				this.close('yb')
			}, 500)
		},
		methods: {
			// 开始找零
			zlSubmit() {
				if (options.type === 'zb') {
					this.handPay(3);
					this.isZLTipShow = true;
				}
				if (options.type === 'yb') {
					this.handPay(3);
					this.isZLTipShow = true;
				}
			},
			// 投币完成
			tbSuccess(options) {
				if (options.type === 'zb') {
					this.isZBSuccessTipShow = true;
					this.change = options.change;
					this.close('zb');
				}
				if (options.type === 'yb') {
					this.isTBSuccessTipShow = true;
					this.change = options.change;
					this.close('yb');
				}
				if (options.type === 'zl') {
					this.close('zl');
				}
			},
			// 获取订单编号
			getOrderCode() {
				const {
					user,
					room,
					order
				} = useStore();
				const params = Object.assign({
						room_id: room.getRoomOptions.id,
						// pay_type: order.getOrderPay.pay_type,
						pay_type: 5,
						// money: order.getOrderObj.money ?
						// 	order.getOrderObj.money.split('.')[0] * 1 :
						// 	'',
						money: order.getOrderObj.money,
						date: `${order.getOrderObj.year}-${order.getOrderObj.date}`,
						timeslot: `${order.getOrderObj.startTime},${order.getOrderObj.endTime}`,
					},
					order.getOrderObj.package_options &&
					order.getOrderObj.package_options.id ? {
						package_id: order.getOrderObj.package_options.id
					} : {}
				);
				console.log('params', params);

				getOrderCode(params)
					.then(res => {
						console.log(res, '獲取訂單號')
						this.isPayErrorShow = false;
						const {
							room,
							order
						} = useStore();
						console.log('res.order_no', res.order_no);
						this.view.order_no = res.order_no;
					})
					.catch(err => {
						this.isPayErrorShow = true;
					});
				this.payable = order.getOrderObj.money ? order.getOrderObj.money : '';
			},
			// 计算纸币投币应找零
			handCountMoney(money) {

				this.change = money;
				this.send('zb', zbCode.money_accept); // 確認收幣  -- 02


				this.isZLOpen = true;

				this.handOpen(3) // 打開找零串口

				// this.send('zl', countZLSend(zlNumber))

				console.log('应找零', money);
			},
			setSwiperImg() {
				const equipmentOptions = JSON.parse(
					uni.getStorageSync('equipmentOptions')
				);
				// console.log('equipmentOptions', equipmentOptions.imagejh);
				// const _src = equipmentOptions.imagejh ?
				// 	equipmentOptions.imagejh.split(',') : [];
				// if (_src.length > 1) {
				// 	this.src = _src.map(item => baseURL + item);
				// } else if (_src.length === 1) {
				// 	this.src = [baseURL + _src[0]];
				// }

				this.src = baseURL + equipmentOptions.image5
			},
			countdown() {
				this.timer = setTimeout(() => {
					// uni.navigateTo({
					// 	url: '/pages/index/index',
					// });
				}, 1000 * 60 * 10);
			},
			clearCountdown() {
				clearTimeout(this.timer);
				this.countdown();
			},
			handPay(index) {
				let count = 0;
				let _index = index;
				let img = '/static/images/1.jpg';
				switch (index) {
					case 1:
						count = 1;
						img = '/static/images/1.jpg';
						// this.isZBTipShow = true;
						// this.showZBPopup = true
						break;
					case 2:
						count = 2;
						img = '/static/images/2.jpg';
						// this.isYBTipShow = true;
						// this.showYBPopup = true
						break;
					case 3:
						count = 3;
						break;
					case 4:
						count = 4;
						// this.showPopup = true
						break;
					case 5:
						count = 5;
						break;
					case 6:
						count = 6;
						break;
					default:
				}
				this.payTypeIndex = count;
				this.tipsImg = img;
				this.handOpen(_index);
			},
			closeFn() {
				this.isCouponShow = false;
			},
			jump(data) {
				let url = '';
				switch (data) {
					case 'register':
						url = '/pages/register/register';
						break;
					case 'codeLogin':
						url = '/pages/menu/menu';
						break;
					case 'scanCode':
						url = '/pages/scanCode/scanCode';
						break;
					case 'pay':
						url = '/pages/pay/ticket';
						break;
					case 'logout':
						url = '/pages/index/index';
						break;
					default:
				}
				uni.navigateTo({
					url
				});
			},
			// 付款公用方法开始
			// 找零异常显示情况
			error() {
				this.isErrorTipShow = true;
			},
			// 打开串口
			handOpen(index) {
				if (index === 1) {
					// this.open('/dev/ttyUSB10', 9600, 'zb');

					// 先關閉硬幣投入串口
					this.send('yb', ybCode.disable)
					this.close('yb')

					this.open('/dev/ttyS6', 9600, 'zb');
				}
				if (index === 2) {
					// this.open('/dev/ttyUSB10', 9600, 'yb');

					// 先關閉紙幣投入串口
					this.send('zb', zbCode.money_disabled)
					this.close('zb')

					this.open('/dev/ttyS7', 9600, 'yb');
				}
				if (index === 3) {
					// this.open('/dev/ttyUSB10', 9600, 'zl');
					this.open('/dev/ttyS8', 9600, 'zl');
					this.isZLPendingTipShow = true;
				}
				if (index === 4) {
					// 同時打開紙幣和硬幣的串口
					this.open('/dev/ttyS6', 9600, 'zb')
					this.send('zb', zbCode.cmd_respond)
					// this.send('zb', zbCode.money_enable)
					setTimeout(() => {
						this.open('/dev/ttyS7', 9600, 'yb')
						this.send('yb', ybCode.reset)
						// this.send('yb', ybCode.run)
					}, 500)
				}
				// if (index === 5) {
				// 	this.open('/dev/ttyS6', 9600, 'zb')
				// }
				// if (index === 6) {
				// 	this.open('/dev/ttyS7', 9600, 'yb');
				// }
			},
			// 确认纸币投币
			handConform(type) {
				if (type == 'zb') {
					this.send('zb', zbCode.money_accept);
				}
				if (type == 'yb') {
					this.send('yb', zbCode.money_accept);
					this.isYBPendingTipShow = true;
				}
				if (type == 'zl') {
					this.send('zl', zbCode.money_accept);
				}
			},
			// 取消本次投币
			handCanel(type) {
				// console.log(type, '查看')
				if (type === 'zb') {
					this.isZBTipShow = false

					// this.send(zbCode.money_refused);
					this.send('zb', zbCode.money_refused);
					this.close('zb')
				}
				if (type === 'yb') {
					this.send(zbCode.money_refused);
				}
				if (type === 'zl') {
					this.send(zbCode.money_refused);
				}
			},
			handClose(type) {
				switch (type) {
					case 'zl':
						this.isZLTipShow = false;
						break;
					case 'zlPending':
						this.isZLPendingTipShow = false;
						break;
					default:
				}
				this.close();
			},
			// 付款公用方法结束
			// 串口开始
			//监听数据
			// 纸币开始
			// 串口公用方法开始
			// 通信数据处理
			addMessage(type, msg, serialType) {

				if (serialType === 'zb') {
					if (type === 'rec') {
						// 當前投入的總金額
						let total = this.analysisCountMoney(this.messageSumArr)
						// 訂單金額
						let amount = this.view.order.money

						if (Number(total) >= Number(amount)) {
							// 當投入的金額大於訂單金額時，就不需要繼續投入金額了
							this.send('zb', zbCode.money_false) // 拒收紙幣
							// uni.showToast({
							// 	title: '當前投入金額已超過訂單金額，無需繼續投入金額了！',
							// 	icon: 'none',
							// 	duration: 2000,
							// })
							this.send('zb', zbCode.money_disabled)
							setTimeout(() => {
								this.close('zb') // 關閉紙幣串口
							}, 500)
							this.send('yb', ybCode.disable)
							setTimeout(() => {
								this.close('yb')
							}, 500)
							return
						}

						// 確認收幣
						this.send('zb', zbCode.money_accept)
						// this.send('zb', zbCode.money_staging)

						this.messageZBArr = [...this.messageZBArr, msg]
						this.messageSumArr = [...this.messageSumArr, msg]

						if (msg == zbCode.money_100 || msg == zbCode.money_500 || msg == zbCode.money_1000) {
							this.sendCoinRecord('zb', msg)
						}
					}
					if (type === 'send') {
						this.messageZBSendArr = [
							...JSON.parse(JSON.stringify(this.messageZBSendArr)),
							msg,
						];

						this.isZBPendingTipShow = true;
						this.isZBTipShow = false;


						this.messageZBSendArr = []

					}
				}
				if (serialType === 'yb') {
					if (type === 'rec') {

						// 當前投入的總金額
						let total = this.analysisCountMoney(this.messageSumArr)
						// 訂單金額
						let amount = this.view.order.money

						if (Number(total) >= Number(amount)) {
							// uni.showToast({
							// 	title: '當前投入金額已超過訂單金額，無需繼續投入金額了！',
							// 	icon: 'none',
							// 	duration: 2000,
							// })
							this.send('zb', zbCode.money_disabled)
							setTimeout(() => {
								this.close('zb')
							}, 500)
							this.send('yb', ybCode.disable)
							setTimeout(() => {
								this.close('yb')
							}, 500)
							return
						}

						// this.messageZBArr = [...this.messageZBArr, msg]
						this.messageYBArr = [...this.messageYBArr, msg]
						this.messageSumArr = [...this.messageSumArr, msg]

						if (msg == ybCode.money_50) {
							this.sendCoinRecord('yb', msg)
						}
					}
					if (type === 'send') {
						this.messageYBSendArr = [
							...JSON.parse(JSON.stringify(this.messageYBSendArr)),
							msg,
						];
						this.isYBPendingTipShow = true;
						this.isYBTipShow = false;
					}
				}
				if (serialType === 'zl') {
					if (type === 'rec') {
						if (msg == zlCode.payout_return) {
							this.changedArr.push(msg)
						}
						this.changed = this.changedArr.length
						this.payoutFinished.push(msg)
						this.messageZLArr = [...this.messageZLArr, msg]

						// 退幣完成返回指令  不管是否完成指定找零數量
						if (msg == zlCode.payout_finished) {
							if (this.changed > this.change) {
								uni.showToast({
									title: '當前繳費機零錢不足，請聯繫管理人員',
									icon: 'none',
									duration: 5000
								})
								this.showZBZLPopup = true
							}
						}

						// 硬幣不足回復指令
						if (msg == zlCode.insufficient_coins) {
							// this.showCoinInsufficient = true
							clearTime()
							clearTimeout(this.quit)
							this.coninInsufficient = true
							// uni.setStorageSync('CoinInsufficient', true)
							this.cacheChangeStatusFn(0)
						} else {
							timeOut()
							this.coninInsufficient = false
							// uni.setStorageSync('CoinInsufficient', false)
							this.cacheChangeStatusFn(1)
						}

						this.isZLPendingTipShow = false;
						this.isZLTipShow = true;
					}
					if (type === 'send') {
						this.messageZLSendArr = [
							...JSON.parse(JSON.stringify(this.messageZLSendArr)),
							msg,
						];
						return
						this.isZLPendingTipShow = true;
						this.isZLTipShow = false;
					}
				}
			},
			//监听数据
			onMessage(type) {
				if (type === 'zb') {
					zbSerialPort.onMessageHex(
						rec => {
							// 串口监听的接收信息，所有接收的信息都走这里
							this.addMessage('rec', rec, 'zb');
						},
						send => {
							// 串口监听的发送信息，所有发送的信息都走这里
							this.addMessage('send', send, 'zb');
						}
					);
				}
				if (type === 'yb') {
					ybSerialPort.onMessageHex(
						rec => {
							// 串口监听的接收信息，所有接收的信息都走这里
							this.addMessage('rec', rec, 'yb');
						},
						send => {
							// 串口监听的发送信息，所有发送的信息都走这里
							this.addMessage('send', send, 'yb');
						}
					);
				}
				if (type === 'zl') {
					zlSerialPort.onMessageHex(
						rec => {
							// 串口监听的接收信息，所有接收的信息都走这里
							this.addMessage('rec', rec, 'zl');
						},
						send => {
							// 串口监听的发送信息，所有发送的信息都走这里
							this.addMessage('send', send, 'zl');
						}
					);
				}
			},
			// 串口公用方法结束
			/**
			 * 关闭串口
			 *
			 */
			close(type) {
				if (type === 'zb') {
					zbSerialPort.close();
				}
				if (type === 'yb') {
					ybSerialPort.close();
				}
				if (type === 'zl') {
					zlSerialPort.close();
				}
			},
			/**
			 * 打开串口
			 * @param {string} url
			 * @param {number} baudRate
			 * @param {string} type
			 * @param {number} zlCount
			 *
			 */
			async open(url, baudRate, type, zlCount) {
				// console.log('url ==> ', url)
				// console.log('baudRate ==> ', baudRate)
				// console.log('type ==>', type)
				// console.log('zlCount ==>', zlCount)
				const _url = url ? url : this.zbUrl;
				const _baudRate = baudRate ? baudRate : this.baudRate;

				// await zlSerialPort.setParity(2);

				if (type === 'zb') {

					await zbSerialPort.setPath(_url);
					await zbSerialPort.setBaudRate(_baudRate);
					await zbSerialPort.setParity(0);
					await zbSerialPort.open(res => {
						if (!res.status) {
							return;
						}

						// uni.showToast({
						// 	title: '纸币串口打开',
						// 	icon: 'success',
						// 	duration: 3000
						// })

						this.isZBOpen = true;
						this.onMessage('zb');
						this.send('zb', zbCode.cmd_respond);
						this.send('zb', zbCode.money_enable);
					});


					/*
					await zbSerialPort.getAllDevicePath(res => {
						zbSerialPort.setPath(_url)
						zbSerialPort.setBaudRate(_baudRate)
						zbSerialPort.open(res => {
							uni.showToast({
								title: '纸币串口 ==>' + res,
								icon: 'none',
								duration: 3000
							})

							this.onMessage('zb');
							this.send('zb', zbCode.cmd_respond);
							this.send('zb', zbCode.money_enable);

						})
					})
					*/

				}
				if (type === 'yb') {

					await ybSerialPort.setPath(_url);
					await ybSerialPort.setBaudRate(_baudRate);
					// await ybSerialPort.setParity(0);
					await ybSerialPort.open(res => {
						if (!res.status) {
							return;
						}
						this.isYBOpen = true;


						// 當前投入的總金額
						let total = this.analysisCountMoney(this.messageSumArr)
						// 訂單金額
						let amount = this.view.order.money

						if (total >= amount) {
							this.send('yb', ybCode.disable)
							this.close('yb')
							// uni.showToast({
							// 	title: '當前投入金額已超過訂單金額，無需繼續投入金額了！',
							// 	icon: 'none',
							// 	duration: 2000
							// })
							return
						}

						this.onMessage('yb');
						this.send('yb', ybCode.run);
					});

					/*
					await zbSerialPort.getAllDevicePath(res => {
						zbSerialPort.setPath(_url)
						zbSerialPort.setBaudRate(_baudRate)
						zbSerialPort.open(res => {
							uni.showToast({
								title: '硬币串口 ==>' + res,
								icon: 'none',
								duration: 3000
							})

							this.onMessage('zb');
							this.send('zb', zbCode.cmd_respond);
							this.send('zb', zbCode.money_enable);

						})
					})
					*/
				}
				if (type === 'zl') {
					await zlSerialPort.setPath(_url);
					await zlSerialPort.setBaudRate(_baudRate);
					await zlSerialPort.setParity(2);
					await zlSerialPort.open(res => {
						if (!res.status) {
							return;
						}
						this.isZLOpen = true;


						// clearTimeout(time)
						this.onMessage('zl');
						// this.send('zl', countZLSend(Math.floor(this.change / 50 || 0)));
						// this.send('zl', zlCode.money_payoutCoin1)

						if (this.payflag) {
							this.send('zl', countZLSend(Math.floor(this.analysisCountMoney(this
								.messageSumArr)) / 50))
						} else {
							this.send('zl', countZLSend(this.change))
						}


						this.showZBZLPopup = true
						// setTimeout(() => {
						// 	this.sendChangeRecord()
						// }, 2000)
						if (this.isBack) return
						this.sendChangeRecord()
						let time = setTimeout(() => {
							this.confirmZLFinish()
						}, 10000)
					});
				}
			},
			/**
			 * 发送消息
			 * @param {string} type 投币口 'zb' | 'zb' | 'zl'
			 * @param {string} sendText 发送的指令
			 *
			 */
			send(type, sendText) {
				const _sendHexText = sendText ? sendText : this.sendHexText;
				if (type === 'zb') {
					if (!this.isZBOpen) {
						return;
					}
					zbSerialPort.sendHex(_sendHexText);

					if (sendText == zbCode.money_accept || sendText == zbCode.money_false) {
						// 當確認或者拒收紙幣的時候清空一次指令數組
						this.instructArr = []
					}
				}
				if (type === 'yb') {
					if (!this.isYBOpen) {
						return;
					}
					ybSerialPort.sendHex(_sendHexText);
				}
				if (type === 'zl') {
					if (!this.isZLOpen) {
						return;
					}
					this.zlcurrent++
					zlSerialPort.sendHex(_sendHexText);
					this.isZBTipShow = false

					// 找零结束，纸币弹窗
					this.showZBPopup = false
					this.showYBPopup = false

				}
			},
			// 串口结束
			logout() {
				if (this.payflag) {
					this.handOpen(3)
				}

				uni.removeStorageSync('userOptions');
				this.send('zb', zbCode.money_disabled)
				setTimeout(() => {
					this.close('zb')
				}, 500)
				this.send('yb', ybCode.disable)
				setTimeout(() => {
					this.close('yb')
				}, 500)
				setTimeout(() => {
					this.close('zl')
				}, 1000)
				this.jump('logout');
			},
			// 解析投入纸币返回的指令并计算总和
			analysisCountMoney(arr) {
				let total = 0
				arr.forEach(item => {
					total += countMoney(item)
				})
				this.submittedMoney = total
				return total
			},
			// 取消投幣
			cancelConining() {
				this.send('zb', zbCode.money_false) // 發送指令，拒收紙幣

				this.committedZBArr = this.committedZBArr.slice(0, this.committedZBArr.length - 1)

				this.showIsZBCoining = false // 關閉確認投入彈窗
				// this.close('zb')
				this.showZBPopup = true

				// 清空指令數組
				// this.instructArr = []
			},
			// 確認投幣
			confirmConining() {
				// this.send('zb', zbCode.money_accept)
				this.showIsZBCoining = false
				setTimeout(() => {
					this.messageZBArr = [...this.committedZBArr]
					this.showZBPopup = true
				}, 1000)

				// 每次确认投币之后清空一次指令数组
				this.messageZBSendArr = []
				// 清空指令數組
				// this.instructArr = []
			},
			// 确认支付
			confirmPay(num) {
				// 確認收幣
				// this.send('zb', zbCode.money_accept)

				this.payTypeIndex = num
				let meet = this.view.order.money
				let actualPayment = this.analysisCountMoney(this.messageSumArr)
				this.paid = actualPayment

				if (!this.payflag) return
				LogCat.d('投幣：', this.messageSumArr, this.view.order_no)
				if (actualPayment < meet) {
					uni.showToast({
						title: '投幣金額不足',
						icon: 'none',
						duration: 2000,
					})
					this.payflag = true
					return
				}
				this.change = Math.floor((Number(actualPayment) - Number(meet)) / 50)

				this.send('zb', zbCode.money_disabled)
				setTimeout(() => {
					this.close('zb') // 關閉投紙幣串口
				}, 500)
				this.send('yb', ybCode.disable)
				setTimeout(() => {
					this.close('yb')
				}, 500)

				// if (this.messageZBArr.length) {
				// 	this.sendCoinRecord(1)
				// } else if (this.messageYBArr.length) {
				// 	this.sendCoinRecord(2)
				// }
				this.showZBPopup = false
				this.showYBPopup = false

				// 將投幣記錄寫入到日誌中
				if (this.change == 0) {
					this.sendCoinPay()
					return
				}
				if (this.change == this.changed) {
					uni.showToast({
						title: '已經支付完成，請勿重複點擊',
						icon: 'none'
					})
					return
				}
				this.payflag = false
				this.handOpen(3) // 打開找零串口


			},
			// 確認找零完成
			confirmZLFinish() {
				const index = this.payoutFinished.indexOf(zlCode.payout_finished)
				// 当不是第一次找零，并且不存在找零完成之后，说明上一次找零操作未完成
				if (this.change > this.changed) {
					if (this.zlcurrent > 0 && index == -1) return
					this.payoutFinished = []
					this.send('zl', countZLSend(this.change - this.changed))
					return
				}

				this.showZBZLPopup = false

				LogCat.d('找零：', this.messageZLArr, this.view.order_no)

				if (this.coninInsufficient) {
					// 硬币不足，可能无法正常找零
					this.showCoinInsufficient = true
				}

				getOrderList({
					page: 1
				}).then(res => {
					let obj = res.filter(item => item.order_no == this.view
						.order_no)[0]

					this.orderId = obj.id
					uni.reLaunch({
						url: `/pages/order/order_details?id=${obj.id}`
					})
				})
			},
			// 
			contactService() {
				this.showCoinInsufficient = false
				// uni.setStorageSync('CoinInsufficient', true)
				uni.reLaunch({
					url: '/pages/index/index'
				})
			},
			closeZBPopup() {
				this.showZBPopup = false
				this.send('zb', zbCode.money_disabled) // 先禁用纸币机，然后再关闭串口
				this.close('zb')
			},
			closeYBPopup() {
				this.showYBPopup = false
				this.send('yb', ybCode.disable)
				this.close('yb')
			},
			// 将投币记录发送至服务器
			sendCoinRecord(amount_type, msg) {
				const equipmentOptions = JSON.parse(uni.getStorageSync('equipmentOptions'))
				let zbNum = this.messageZBArr.filter(item => {
					if (item == zbCode.money_100 || item == zbCode.money_500 || item == zbCode.money_1000) {
						return item
					}
				})
				let zbSum = this.analysisCountMoney(zbNum)
				let ybNum = this.messageYBArr.filter(item => item == ybCode.money_50)
				let ybSum = this.analysisCountMoney(ybNum)

				// let params = {
				// 	store_id: equipmentOptions.id,
				// 	order_no: this.view.order_no,
				// 	equipmentID: equipmentOptions.equipmentID,
				// 	amount: type == 1 ? this.analysisCountMoney(this.messageZBArr) : this.analysisCountMoney(this
				// 		.messageYBArr),
				// 	amount_type: type, //  1--纸币  2--硬币
				// 	type: 1, //  1--投币  2--找零
				// 	num: type == 1 ? zbNum.length : ybNum.length,
				// 	denomination: type == 1 ? zbSum : ybSum,
				// }

				let denomination = ''
				switch (msg) {
					case zbCode.money_100:
						denomination = 100
						break;
					case zbCode.money_500:
						denomination = 500
						break;
					case zbCode.money_1000:
						denomination = 1000
						break;
					case ybCode.money_50:
						denomination = 50
						break;
				}

				let params = {
					store_id: equipmentOptions.id,
					order_no: this.view.order_no,
					equipmentID: equipmentOptions.equipmentID,
					amount: denomination,
					amount_type: amount_type == 'zb' ? 1 : 2,
					type: 1,
					num: 1,
					denomination: denomination,
				}

				saveSlotLog(params).then(res => {

				})

			},
			// 将找零记录发送至服务器
			sendChangeRecord() {
				const equipmentOptions = JSON.parse(uni.getStorageSync('equipmentOptions'))
				let params = {
					store_id: equipmentOptions.id,
					order_no: this.view.order_no,
					equipmentID: equipmentOptions.equipmentID,
					amount: Number(this.change) * 50,
					amount_type: 2, //  1--纸币  2--硬币
					type: 2, //  1--投币  2--找零
					num: this.change,
					denomination: 50,
				}

				saveSlotLog(params).then().then(() => {
					this.sendCoinPay()
				})
			},
			// 處理支付結果
			sendCoinPay() {

				// 判断是否是续单
				if (this.extendFlag) {
					const {
						order
					} = useStore()
					const params = order.getExtendInfo

					orderContinuation(params).then(res => {
						if (res.code == 0) {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							})
							this.payflag = true
						} else {
							uni.showToast({
								title: '續單成功',
								icon: 'success',
								duration: 2000
							})
							this.payflag = false
							if (this.change == 0) {
								setTimeout(() => {
									getOrderList({
										page: 1
									}).then(res => {
										let id = params.order_id
										uni.reLaunch({
											url: `/pages/order/order_details?id=${id}`
										})
									})
									// this.logout()
								}, 2000)
							}
						}
					})
					return
				}

				const params = {
					order_no: this.view.order_no,
					pay_price: this.view.order.money,
					order_status: 1,
					pay_type: 5
				}
				saveSlotPay(params).then(res => {
					if (res.code || res.code == 0) {
						uni.showToast({
							title: res.msg,
							icon: 'none',
						})
						this.payflag = true
					} else {
						uni.showToast({
							title: '支付成功',
							icon: 'success',
							duration: 2000
						})
						this.payflag = false

						if (this.change == 0) {
							setTimeout(() => {
								getOrderList({
									page: 1
								}).then(res => {
									let obj = res.filter(item => item.order_no == this.view
										.order_no)[0]

									this.orderId = obj.id
									uni.reLaunch({
										url: `/pages/order/order_details?id=${obj.id}`
									})
								})
								// this.logout()
							}, 2000)
						}
					}
				})
			},
			closePopup() {
				this.send('zb', zbCode.money_disabled)
				this.close('zb')
				this.send('yb', ybCode.disable)
				this.close('yb')
				this.showPopup = false
			},
			retreat() {
				// 有投幣的話自動退出
				// this.send('zb', zbCode.money_refused)
				this.isBack = true
				if (this.payflag) {
					this.handOpen(3)
				}

				this.send('zb', zbCode.money_disabled)
				setTimeout(() => {
					this.close('zb')
				}, 500)
				this.send('yb', ybCode.disable)
				setTimeout(() => {
					this.close('yb')
				}, 500)
				setTimeout(() => {
					this.close('zl')
				}, 1000)
				uni.reLaunch({
					url: '/pages/predetermine/predetermine'
				})
			},
			cacheChangeStatusFn(status) {
				const equipmentOptions = JSON.parse(uni.getStorageSync('equipmentOptions'));
				const params = {
					type: 2, // 1--查询状态   2--存入状态
					status, // 0--零钱不足   1--零钱充足
					equipmentID: equipmentOptions.equipmentID
				}
				cacheChangeStatus(params)
			}
		},
		watch: {
			submittedMoney(n) {
				if (Number(n) >= Number(this.view.order.money)) {
					this.send('yb', ybCode.disable)
					setTimeout(() => {
						this.close('yb')
					}, 500)
					this.send('zb', zbCode.money_disabled)
					setTimeout(() => {
						this.close('zb')
					}, 500)

					// 當投入的金額足夠之後自動進行支付操作
					this.confirmPay()
				}
			},
			longTime(n) {
				if (n) {
					this.text1 = '長時間未操作，將在一分鐘後自動登出'
				} else {
					this.text1 = '請投入現金'
				}
			},
		}
	};
</script>

<style lang="scss" scoped>
	.predetermine {
		height: 100%;

		.img_box {
			// padding: 40rpx 40rpx 0;
			position: relative;

			.back {
				position: fixed;
				left: 10rpx;
				bottom: 30rpx;
				display: flex;
				align-items: center;
				color: #fff;
				background-color: #ff914d;
				padding: 5rpx 10rpx;
				border-radius: 20rpx;
				z-index: 11;

				image {
					width: 50rpx;
					margin-right: 10rpx;
				}
			}

			.count_down {
				position: absolute;
				right: 10rpx;
				top: 10rpx;
				display: flex;
				align-items: center;
				color: #ff914d;
				font-weight: 600;
				font-size: 32rpx;

				::v-deep .u-count-down {
					// margin-right: 10rpx;
				}

				::v-deep .u-count-down__text {
					color: #ff914d;
					font-size: 32rpx;
					font-weight: 600;
				}
			}
		}

		.main {
			padding: 20rpx;
			color: #39B19D;

			.title {
				padding-bottom: 20rpx;
				font-size: 24rpx;
				display: flex;
				justify-content: space-between;
			}

			.room_info {
				padding: 20rpx 0;
				font-size: 26rpx;
				background-color: $uni-color-white;

				&_box {
					display: flex;
					justify-content: space-between;

					.room_info_l {
						width: 210rpx;
						height: 174rpx;
						padding-left: 20rpx;

						::v-deep .u-image {
							width: 210rpx !important;
							height: 174rpx !important;
						}

						::v-deep .u-image__image {
							width: 100% !important;
							height: 100% !important;
						}

						::v-deep .u-image__loading {
							width: 100% !important;
							height: 100% !important;
						}

						::v-deep .u-image__error {
							width: 100% !important;
							height: 100% !important;
						}
					}

					.room_info_r {
						width: 350rpx;
						// flex: 1;
						// height: 174rpx;
						padding-left: 20rpx;
						display: flex;
						flex-direction: column;
						// justify-content: space-between;

						.btn_box {
							width: 120rpx;
							height: 24rpx;
							padding: 10rpx;
							border: 2rpx solid #39B19D;
							text-align: center;
							line-height: 1;
							border-radius: 5rpx;
						}

						.active {
							color: $uni-color-white;
							background-color: #39B19D;
						}

						.tips {
							color: #39B19D;
						}

						.tips_title {
							margin: 0 0 10rpx;
						}

						.tips_item {
							margin-bottom: 10rpx;
							font-size: 22rpx;
						}

						// .custom-style{
						// 	width: 80rpx;
						// 	height: 24rpx;
						// 	padding: 10rpx;
						// }
					}
				}
			}
		}

		.footer {
			.bot_nav_btn_box {
				position: fixed;
				left: 0;
				bottom: 0;
				width: 100%;
				height: 100rpx;
				line-height: 100rpx;
				background-color: $uni-color-white;

				.container {
					width: 100%;
					display: flex;
					justify-content: space-between;
					font-size: 30rpx;

					.describe {
						padding-left: $uni-spacing-row-base;
						text-align: left;
						color: $uni-color-red-light;
					}

					.btn {
						width: 300rpx;
						text-align: center;
						background-color: #39B19D;
						color: $uni-color-white;
					}
				}
			}

			.notice {
				padding-top: 20rpx;
				height: 100rpx;
			}
		}

		.feature {
			position: relative;
		}
	}

	.zb_popup {
		width: 600rpx;
		padding: 20rpx 30rpx;
		border-radius: 20rpx;
		text-align: center;

		.title {}

		.payable {
			margin: 30rpx 0;
		}

		.committed {
			margin-bottom: 30rpx;
		}

		.btns {
			width: 100%;
			display: flex;
			justify-content: space-between;

			.custom-style1 {
				width: 45%;
			}

			.custom-style2 {
				width: 45%;
				background-color: #39B19D;
				color: #fff;
			}
		}
	}

	.zl_popup {
		width: 600rpx;
		padding: 20rpx 30rpx;
		border-radius: 20rpx;
		text-align: center;

		.zl_popup_item {
			margin-bottom: 30rpx;
		}

		.custom-style3 {
			background-color: #39B19D;
			color: #fff;
		}
	}

	.yb_popup {
		padding: 20rpx 30rpx;
		width: 550rpx;
		text-align: center;

		.img {
			width: 150rpx;
			margin: 20rpx auto;

			image {
				width: 100%;
			}
		}

		.payable {
			margin-bottom: 20rpx;
		}

		.btns {
			display: flex;
			margin: 20rpx 0;
			justify-content: space-between;

			.custom-style1 {
				width: 45%;
			}

			.custom-style2 {
				width: 45%;
				background-color: #39B19D;
				color: #fff;
			}
		}
	}

	.popup_box {
		width: 500rpx;
		padding: 20rpx;
		text-align: center;

		.btns {
			display: flex;
			margin: 20rpx 0;
			justify-content: space-between;

			.custom-style1 {
				width: 45%;
			}

			.custom-style2 {
				width: 45%;
				background-color: #39B19D;
				color: #fff;
			}
		}
	}

	.confirm_pay {
		margin-top: 30rpx;

		.custom-style {
			width: 500rpx;
			background-color: #39B19D;
			color: #fff;
		}
	}
</style>